import { Injectable, Inject } from '@angular/core';

import { Observable } from 'rxjs/observable';
import { Store } from '@ngrx/store';
import { AppState } from '../entity/appState.model';
import { Borrow } from '../entity/borrow.model';
import * as BorrowActions from '../actions/borrow.action';

// service
import { ToastService } from '../utils/toast.service';
import { LoadingService } from '../utils/loading.service';
import { AlertService } from '../utils/alert.service';
import { GeolocationService } from '../utils/geolocation.service';

// 常量
import * as PageConstant from '../../constant/pageConstant';
import * as Constant from '../../constant/constant';

/*** 借款信息相关服务
* */
// sdk 禾穆
declare const hmApi;
@Injectable()
export class BorrowService {
  constructor(
    private toastCtrl: ToastService,
    private loadingCtrl: LoadingService,
    private alertCtrl: AlertService,
    private store$: Store<AppState>,
    private geolocationService: GeolocationService,
    @Inject('user') private userService,
  )
  { }

  /*** 获取借款store
   * */
  public getBorrow(): Observable<Borrow>
  {
    return this.store$.select(AppState => AppState.borrow);
  }

  /*** 获取借款进度
   * 1.1 查询用户借款进度API
   * */
  private getUserOrderProgress(): Promise<any>
  {
    return new Promise((resolve, reject) => {
      hmApi.getUserOrderProgress({},(err, result)=>{
        if(err) {
          reject(err);
          return;
        }
        // 返回
        resolve(result);
      });
    });
  }

  /*** 获取借款进度
   * 1.2 查询用户借款进度条目。
   * @param refresher Refresher
   * */
  public getUserBorrowProgress(refresher): void
  {
    this.getUserOrderProgress().then(result=>{
      if(!result){
        if(refresher){ refresher.complete(); }
        this.store$.dispatch(new BorrowActions.GetBorrowProgressFailedAction());
        return;
      }

      // 若获取成功,
      if(refresher){ refresher.complete(); }
      this.store$.dispatch(new BorrowActions.GetBorrowProgressSuccessAction(result));

    }).catch(err=> {
      if(refresher){ refresher.complete(); }
      this.toastCtrl.createCenterToast(Constant.SERVE_ERROR);
      console.log(err);
    });

  }

  /*** 获取借款额度和事件
   * 2.1 查询默认的借款二维数组
   * @param refresher Refresher
  * */
  public getAppBorrowPickerDefault(refresher): void
  {
    hmApi.getAppDefault({},(err, result)=>{
      const data= eval("("+result.quotaConfig+")");
      if(err) {
        if(refresher){ refresher.complete(); }
        this.toastCtrl.createCenterToast(Constant.SERVE_ERROR);
        console.error(err);
        return;
      }

      if(!data) {
        if(refresher){ refresher.complete(); }
        this.toastCtrl.createCenterToast(Constant.SERVE_ERROR);
        return;
      }
      // 若获取成功
      if(refresher){ refresher.complete(); }
      this.store$.dispatch(new BorrowActions.GetPickerDefaultAction(data));

    });
  }

  /*** 获取借款额度和事件
   * 2.2.1 登录成功查询用户额度API
   * */
  public getUserPickerApi(): Promise<any>
  {
    return new Promise((resolve, reject) => {
      hmApi.getUserPicker({},(err, result)=>{
        if(err) {
          reject(err);
          return;
        }
        if(!result) {
          reject(Constant.SERVE_ERROR);
          return;
        }
        // 返回
        resolve(result);
      });
    });
  }
  /** 查询用户背景额度
   * 2.2.2 登录成功查询用户权限背景API
   */
  private getQuotaListApi(): Promise<any>
  {
    return new Promise((resolve, reject) => {
      hmApi.getUserQuota({},(err, result)=>{
        if(err) {
          reject(err);
          return;
        }
        if(!result) {
          reject(Constant.SERVE_ERROR);
          return;
        }
        // 返回
        resolve(result);
      });
    })
  }

  /*** 获取借款额度或借款进度(登录成功查询用户额度。)
   * 2.3 初始化进入先查询背景额度,进度为空,获取借款数据; 进度不为空,获取进度数据。
   * @param refresher Refresher
  * */
  public getUserBorrowModalDate(refresher): void
  {
    this.getQuotaListApi().then(result=>{
      // 若获取成功
      if(!result) return;

      this.store$.dispatch(new BorrowActions.GetUserQuotaAction(result));
      return this.getUserOrderProgress()
    })
    .then(result=>{
      if(!result) return this.getUserPickerApi();

      // 若获取成功
      if(refresher){ refresher.complete(); }
      this.store$.dispatch(new BorrowActions.GetBorrowProgressSuccessAction(result));
      // 初始化用户信息
      this.userService.getUserInfoFromBack(refresher);

    }).then(result=>{
      // 若获取成功
      if(!result) return;

      this.store$.dispatch(new BorrowActions.GetPickerUserAction(result));
      // 初始化用户信息
      this.userService.getUserInfoFromBack(refresher);

    }).catch(err=> {
      if(refresher){ refresher.complete(); }
      this.toastCtrl.createCenterToast(Constant.SERVE_ERROR);
      console.log(err);
    });
  }

  /*** 点击借款按钮
   * 3.1 借款详情缓存API
   * @param options { amount, timeLimit } 借款金额,借款期限
  * */
  public getBorrowDetailsApi(options: any): Promise<any>
  {
    // 去获取用户信息。这里需要银行卡信息
    const {  amount, timeLimit }= options;
    return new Promise((resolve, reject) =>{
      hmApi.getLoanDetails({ amount, timeLimit },(err, result)=>{
        if(err) {
          reject(err);
          return;
        }
        resolve(result);
      });
    });
  }
  /*** 点击借款按钮
   * 3.2 借款详情缓存
   * @param options { amount, timeLimit } 借款金额,借款期限
   * @param navCtrl NavController
  * */
  public getBorrowDetails(options: any, navCtrl): void
  {
    // 去获取用户信息。这里需要银行卡信息
    this.loadingCtrl.createLoading('加载中');
    this.getBorrowDetailsApi(options).then(result=>{

      // 若获取成功 loan为true就是认证通过
      if(result.loan)
      {
        const { bankName, bankNo, amount, timeLimit }= options;
        const {  arrival, fee }= result;
        const data= {  amount, timeLimit, arrival, fee, bankName , bankNo };
        this.loadingCtrl.closeLoading().then(()=>{
          navCtrl.push(PageConstant.BorrowApplyPage,{
            data: data
          });
        });

        return;
      }
      // 未认证状态
      this.loadingCtrl.closeLoading().then(()=>{
        this.alertCtrl.createAgreeAlert('请先完成认证个人信息')
          .then(data=>{
            navCtrl.push(PageConstant.AuthenticationCenterPage);
        })
      });
    }).catch(err=>{
      this.loadingCtrl.closeLoading().then(()=>{
        this.toastCtrl.createCenterToast(Constant.SERVE_ERROR);
        console.error(err);
      });
    });
  }

  /*** 点击立即申请
   * 4.1 申请订单API
   * @param options { amount, timeLimit } 借款金额,借款期限
   * */
  private createTradeByUser(options): Promise<any>
  {
    const { amount, timeLimit, address, coordinate }= options;
    return new Promise((resolve, reject) =>{
      hmApi.createTrade({ amount, timeLimit, address, coordinate },(err, result)=> {
        if (err) {
          reject(err);
          return;
        }
        resolve(result);
      });
    });

  }

  /*** 点击立即申请
   * 4.2 申请生成订单
   * @param options { amount, timeLimit } 借款金额,借款期限
   * @param navCtrl NavController
  * */
  public getBorrowApply(options, navCtrl)
  {
    this.loadingCtrl.createLoading('加载中');
    let x, y;
    this.geolocationService.initGeolocation().then(resp => {
      x = resp.coords.longitude;
      y = resp.coords.latitude;
      return this.geolocationService.getAddress(x, y);
    }).then(result=>{
      const address= result;
      const coordinate=`${x},${y}`;
      return this.createTradeByUser({...options, address, coordinate});
    })
   /*** 去除百度地图定位
   this.geolocationService.getBaiduLocation().then(({x, y ,address})=>{
      debugger;
      const coordinate=`${x},${y}`;
      return this.createTradeByUser({...options, address, coordinate});
    })*/
      .then(result=>{
      // 若创建成功
      this.loadingCtrl.closeLoading().then(() => {
        // 若获取成功
        this.store$.dispatch(new BorrowActions.UpdateBorrowModalAction());
        this.alertCtrl.createMessageAlert('提示','借款提交成功,系统审核中,请耐心等待')
          .then(data=>{
          navCtrl.pop();
        })
      });
    }).catch(err => {

      this.loadingCtrl.closeLoading().then(()=>{
        this.toastCtrl.createCenterToast(Constant.SERVE_ERROR);
        console.log('Error message', err);
      });
    });
  }

}
